package com.joolun.web.controller.scrm;

import java.util.*;
import java.util.stream.Collectors;

import com.joolun.weixin.entity.ScrmChannelRecordLog;
import com.joolun.weixin.entity.vo.ScrmChannelRecordLogVo;
import com.joolun.weixin.service.IScrmChannelRecordLogService;
import com.joolun.weixin.service.IScrmChannelStatisticsService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.joolun.common.annotation.Log;
import com.joolun.common.core.controller.BaseController;
import com.joolun.common.core.domain.AjaxResult;
import com.joolun.common.enums.BusinessType;
import com.joolun.system.domain.ScrmChannelStatistics;
import com.joolun.common.utils.poi.ExcelUtil;
import com.joolun.common.core.page.TableDataInfo;

/**
 * 渠道数据统计Controller
 * 
 * @author joolun
 * @date 2025-03-19
 */
@RestController
@RequestMapping("/system/statistics")
public class ScrmChannelStatisticsController extends BaseController
{
    @Autowired
    private IScrmChannelStatisticsService scrmChannelStatisticsService;

    @Autowired
    private IScrmChannelRecordLogService scrmChannelRecordLogService;
    /**
     * 查询渠道数据统计列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ScrmChannelStatistics scrmChannelStatistics)
    {
        startPage();
        List<ScrmChannelStatistics> list = scrmChannelStatisticsService.selectScrmChannelStatisticsList(scrmChannelStatistics);
        return getDataTable(list);
    }
    /**
     * 渠道数据汇总列表
     */
    @GetMapping("/summary")
    public TableDataInfo summary(@RequestParam Map<String, Object> params)
    {
        startPage();
        List<ScrmChannelStatistics> list = scrmChannelStatisticsService.summary(params);
        return getDataTable(list);
    }
    /**
     * 折线图统计
     */
    @GetMapping("/chart")
    public AjaxResult chart(@RequestParam Map<String, Object> params)
    {
        List<ScrmChannelRecordLogVo> list = scrmChannelRecordLogService.selectChart(params);
        // 按小时分组
        Map<String, Map<String, String>> hourGroup = list.stream()
                .collect(Collectors.groupingBy(
                        ScrmChannelRecordLogVo::getHourPart,  // 按小时分组
                        LinkedHashMap::new,
                        Collectors.toMap(
                                ScrmChannelRecordLogVo::getType,  // 类型作为键
                                ScrmChannelRecordLogVo::getCountNum,  // 值作为值
                                (existing, replacement) -> existing,  // 冲突策略（通常不会冲突）
                                TreeMap::new  // 使用 TreeMap 保证按小时排序
                        )
                ));

        // 构建结果
        Map<String, List<String>> result = new LinkedHashMap<>();
        List<String> hours = new ArrayList<>();

        // 初始化各类型的数组
        List<String> pvList = new ArrayList<>();
        List<String> liuZiList = new ArrayList<>();
        List<String> jvList = new ArrayList<>();
        List<String> joinGroupList = new ArrayList<>();
        // 填充数据
        for (Map.Entry<String, Map<String, String>> entry : hourGroup.entrySet()) {
            String hour = entry.getKey();
            Map<String, String> typeMap = entry.getValue();

            hours.add(hour);
            pvList.add(typeMap.getOrDefault("PV", "0"));
            liuZiList.add(typeMap.getOrDefault("liuZi", "0"));
            jvList.add(typeMap.getOrDefault("JV", "0"));
            joinGroupList.add(typeMap.getOrDefault("joinGroup", "0"));
        }

        // 放入结果 Map
        result.put("hours", hours);
        result.put("PV", pvList);
        result.put("liuZi", liuZiList);
        result.put("JV", jvList);
        result.put("joinGroup", jvList);
        return success(result);
    }
    /**
     * 导出渠道数据统计列表
     */
    @PreAuthorize("@ss.hasPermi('system:statistics:export')")
    @Log(title = "渠道数据统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScrmChannelStatistics scrmChannelStatistics)
    {
        List<ScrmChannelStatistics> list = scrmChannelStatisticsService.selectScrmChannelStatisticsList(scrmChannelStatistics);
        ExcelUtil<ScrmChannelStatistics> util = new ExcelUtil<ScrmChannelStatistics>(ScrmChannelStatistics.class);
        util.exportExcel(response, list, "渠道数据统计数据");
    }

    /**
     * 获取渠道数据统计详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(scrmChannelStatisticsService.selectScrmChannelStatisticsById(id));
    }

    /**
     * 新增渠道数据统计
     */
    @PreAuthorize("@ss.hasPermi('system:statistics:add')")
    @Log(title = "渠道数据统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScrmChannelStatistics scrmChannelStatistics)
    {
        scrmChannelStatistics.setCreateBy(getUsername());
        return toAjax(scrmChannelStatisticsService.insertScrmChannelStatistics(scrmChannelStatistics));
    }

    /**
     * 修改渠道数据统计
     */
    @PreAuthorize("@ss.hasPermi('system:statistics:edit')")
    @Log(title = "渠道数据统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScrmChannelStatistics scrmChannelStatistics)
    {
        scrmChannelStatistics.setCreateBy(getUsername());
        return toAjax(scrmChannelStatisticsService.updateScrmChannelStatistics(scrmChannelStatistics));
    }

    /**
     * 删除渠道数据统计
     */
    @PreAuthorize("@ss.hasPermi('system:statistics:remove')")
    @Log(title = "渠道数据统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scrmChannelStatisticsService.deleteScrmChannelStatisticsByIds(ids));
    }
}
